<?php

namespace App\Http\Requests\Admin;

use App\Http\Models\App\App;
use App\Http\Models\App\AppGroup;
use App\Http\Models\Staff\Staff;
use App\Http\Models\Staff\StaffAppGroupRelation;
use App\Http\Models\Staff\StaffAppRelation;
use App\Http\Models\Staff\StaffDept;
use App\Http\Models\Staff\StaffPost;
use App\Http\Requests\Common\BaseRequest as Request;

class StaffRequest extends Request
{
    //
    public function staff()
    {
        $keys = ['rows', 'type', 'page', 'sort', 'order', 'dept_id', 'name', 'status'];
        $data = $this->only($keys);
        if ($data['type'] == 'ajax') {
            $model = Staff::where(function ($query) use ($data) {
                if ($data['name']) {
                    $query->where('name', 'like', "%{$data['name']}%");
                }
                if ($data['dept_id']) {
                    $query->where('dept_id', $data['dept_id']);
                }
                if ($data['status']) {
                    $status = $data['status'] == 2 ? 0 : $data['status'];
                    $query->where('status', $status);
                }
            });
            $staffs = $model->orderBy($data['sort'], $data['order'])->paginate($data['rows']);
            $data   = [
                'total' => $staffs->total(),
                'rows'  => $staffs->getCollection(),
            ];
            return \Response::json($data);
        }
        //
        $apps       = self::_toArray(App::where('status', 1)->select('id', 'name')->get());
        $groups     = self::_toArray(AppGroup::where('status', 1)->select('id', 'name', 'app_id')->get());
        $appsGroups = [];
        foreach ($apps as $app) {
            $appsGroups[$app['id']]['id']     = $app['id'];
            $appsGroups[$app['id']]['name']   = $app['name'];
            $appsGroups[$app['id']]['groups'] = [];
        }
        //
        foreach ($groups as $group) {
            $_group = [
                'id'   => $group['id'],
                'name' => $group['name'],
            ];
            if (!isset($appsGroups[$group['app_id']])) {
                $appsGroups[$group['app_id']]['id']     = $group['app_id'];
                $appsGroups[$group['app_id']]['name']   = $group['app_id'];
                $appsGroups[$group['app_id']]['groups'] = [];
            }
            $appsGroups[$group['app_id']]['groups'][] = $_group;
        }
        //
        $depts = self::_toArray(StaffDept::where('status', 1)->select('id', 'name')->get());
        $posts = self::_toArray(StaffPost::where('status', 1)->select('id', 'name', 'code')->get());
        //
        $deptArr = [];
        foreach ($depts as $dept) {
            $deptArr[$dept['id']] = $dept['name'];
        }
        $postArr = [];
        foreach ($posts as $post) {
            $postArr[$post['id']] = $post['name'] . "-{$post['code']}";
        }

        $data = [
            'apps'       => $apps,
            'appsGroups' => $appsGroups,
            'depts'      => $depts,
            'posts'      => $posts,
            'deptJson'   => json_encode($deptArr),
            'postJson'   => json_encode($postArr),
        ];
        return View('admin.app.staff', compact('data'));
    }
    //
    public function staff_add()
    {
        //动态验证发送过来的数据
        $rules = [
            "dept_id"  => "required|exists:staff_dept,id",
            "post_id"  => "required|exists:staff_post,id",
            "name"     => "required|min:2|max:20",
            "account"  => "required|min:2|max:20|unique:staff",
            "mobile"   => "required|min:2|max:80|unique:staff",
            "email"    => "required|min:2|max:80|unique:staff",
            "password" => "required|min:2|max:80",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "unique"   => ":attribute已经存在",
            "exists"   => ":attribute不存在",
        );
        $attributes = array(
            "dept_id"  => "部门ID",
            "post_id"  => "职称ID",
            "name"     => "真实姓名",
            "account"  => "用户账号",
            "mobile"   => "用户手机",
            "email"    => "用户邮箱",
            "password" => "用户密码",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //数据入库
        $clean = [
            'dept_id'       => $data['dept_id'],
            'post_id'       => $data['post_id'],
            'name'          => $data['name'],
            'account'       => $data['account'],
            'mobile'        => $data['mobile'],
            'email'         => $data['email'],
            'password'      => md5($data['password']),
            'status'        => 1,
            'operator_id'   => $this->admin['id'],
            'operator_name' => $this->admin['name'],
            'created_at'    => date('Y-m-d H:i:s'),
        ];
        if (!Staff::insert($clean)) {
            return self::_json([], -1, '新增失败!');
        }
        return self::_json();
    }
    //
    public function staff_edit()
    {
        //动态验证发送过来的数据
        $rules = [
            "id"       => "required|exists:staff",
            "dept_id"  => "required|exists:staff_dept,id",
            "post_id"  => "required|exists:staff_post,id",
            "name"     => "required|min:2|max:20",
            "account"  => "required|min:2|max:20",
            "mobile"   => "required|min:2|max:80",
            "email"    => "required|min:2|max:80",
            "status"   => "required",
            "password" => "",
            "type"     => "",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "unique"   => ":attribute已经存在",
            "exists"   => ":attribute不存在",
        );
        $attributes = array(
            "id"      => "用户ID",
            "dept_id" => "部门ID",
            "post_id" => "职称ID",
            "name"    => "用户名称",
            "account" => "用户账号",
            "mobile"  => "用户手机",
            "email"   => "用户邮箱地址",
            "status"  => "用户状态",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //检查用户账号+用户手机+用户邮箱是否重复
        $_id = Staff::where(function ($query) use ($data) {
            $query->where('account', $data['account']);
            $query->orWhere('mobile', $data['mobile']);
            $query->orWhere('email', $data['email']);
        })->pluck('id');
        //
        if (isset($_id) && ($data['id'] != $_id)) {
            return self::_json([], 1, '账号、电话或邮件重复！');
        }
        //更新数据
        $clean = [
            'dept_id'       => $data['dept_id'],
            'post_id'       => $data['post_id'],
            'name'          => $data['name'],
            'account'       => $data['account'],
            'mobile'        => $data['mobile'],
            'email'         => $data['email'],
            'status'        => $data['status'],
            'operator_id'   => $this->admin['id'],
            'operator_name' => $this->admin['name'],
            'updated_at'    => date('Y-m-d H:i:s'),
        ];
        //重置密码
        if ($data['type'] == 'resetPwd') {
            $clean['password'] = md5($data['password']);
        }
        //
        if (!Staff::where('id', $data['id'])->update($clean)) {
            return self::_json([], -1, '更新失败!');
        }
        return self::_json();
    }
    //
    public function staff_apps()
    {
        $keys = ['staff_id'];
        $data = $this->only($keys);
        if ($this->ajax()) {
            //获取用户关联apps以及权限角色组
            $apps = \DB::connection('cas')->table('staff_app_relation as app')
                ->select('app.app_id', 'app.status', 'group.group_id')
                ->join('staff_app_group_relation as group', function ($join) {
                    $join->on('app.staff_id', '=', 'group.staff_id');
                    $join->on('app.app_id', '=', 'group.app_id');
                })
                ->where('app.staff_id', $data['staff_id'])
                ->get();
            return self::_json($apps);
        }
    }
    //
    public function staff_apps_relation_edit()
    {
        if (!$this->ajax()) {
            return self::_json();
        }
        $rules = [
            "staff_id"  => "required|exists:staff,id",
            "relations" => "required",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "exists"   => ":attribute不存在",
        );
        $attributes = array(
            "staff_id"  => "员工ID",
            "relations" => "关联数组",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //把用户关联的app状态改为禁用
        $staff_apps_id = StaffAppRelation::where('staff_id', $data['staff_id'])->pluck('id');
        if ($staff_apps_id) {
            $clean = [
                'status'        => 0,
                'operator_id'   => $this->admin['id'],
                'operator_name' => $this->admin['name'],
                'deleted_at'    => date('Y-m-d H:i:s'),
            ];
            //
            if (!StaffAppRelation::where('staff_id', $data['staff_id'])->update($clean)) {
                return self::_json([], -1, '更新用户关联所有App状态失败!');
            }
        }
        //把用户关联的app状态改为启用，并且把角色组进行关联
        foreach ($data['relations'] as $relation) {
            if ($relation) {
                //更新或者插入用户关联app信息
                $staff_app_relation_id = StaffAppRelation::where('staff_id', $data['staff_id'])->where('app_id', $relation['app_id'])->pluck('id');
                //
                if ($staff_app_relation_id) {
                    $clean = [
                        'status'        => 1,
                        'operator_id'   => $this->admin['id'],
                        'operator_name' => $this->admin['name'],
                        'deleted_at'    => '00-00-00 00:00:00',
                        'updated_at'    => date('Y-m-d H:i:s'),
                    ];
                    if (!StaffAppRelation::where('id', $staff_app_relation_id)->update($clean)) {
                        return self::_json([], -1, '更新用户关联App状态失败!');
                    }
                } else {
                    $clean = [
                        'staff_id'      => $data['staff_id'],
                        'app_id'        => $relation['app_id'],
                        'status'        => 1,
                        'operator_id'   => $this->admin['id'],
                        'operator_name' => $this->admin['name'],
                        'created_at'    => date('Y-m-d H:i:s'),
                    ];
                    if (!StaffAppRelation::insert($clean)) {
                        return self::_json([], -1, '新增用户关联App信息失败!');
                    }
                }
                //更新或者插入用户app以及用户组信息
                $app_staff_group_relation_id = StaffAppGroupRelation::where('staff_id', $data['staff_id'])
                    ->where('app_id', $relation['app_id'])
                    ->pluck('id');
                //
                if ($app_staff_group_relation_id) {
                    $clean = [
                        'group_id'      => $relation['group_id'],
                        'operator_id'   => $this->admin['id'],
                        'operator_name' => $this->admin['name'],
                        'updated_at'    => date('Y-m-d H:i:s'),
                    ];
                    if (!StaffAppGroupRelation::where('id', $app_staff_group_relation_id)->update($clean)) {
                        return self::_json([], -1, '更新用户关联角色组失败!');
                    }
                } else {
                    $clean = [
                        'staff_id'      => $data['staff_id'],
                        'app_id'        => $relation['app_id'],
                        'group_id'      => $relation['group_id'],
                        'operator_id'   => $this->admin['id'],
                        'operator_name' => $this->admin['name'],
                        'created_at'    => date('Y-m-d H:i:s'),
                    ];
                    if (!StaffAppGroupRelation::insert($clean)) {
                        return self::_json([], -1, '新增用户关联角色组失败!');
                    }
                }
            }
        }
        return self::_json();
    }
    //
    public function dept()
    {
        $keys = ['rows', 'type', 'page', 'sort', 'order', 'name', 'app_id', 'status'];
        $data = $this->only($keys);
        if ($data['type'] == 'ajax') {
            $model = StaffDept::where(function ($query) use ($data) {
                if ($data['name']) {
                    $query->where('name', 'like', "%{$data['name']}%");
                }
                if ($data['status']) {
                    $status = $data['status'] == 2 ? 0 : $data['status'];
                    $query->where('status', $status);
                }
            });
            $depts = $model->orderBy($data['sort'], $data['order'])->paginate($data['rows']);
            $data  = [
                'total' => $depts->total(),
                'rows'  => $depts->getCollection(),
            ];
            return \Response::json($data);
        }
        $data = [];
        return View('admin.app.dept', compact('data'));
    }
    //
    public function dept_add()
    {
        //动态验证发送过来的数据
        $rules = [
            "name"      => "required|min:2|max:20|unique:staff_dept",
            "telephone" => "required|min:2|max:20",
            "leader"    => "required|min:2|max:80",
            "desc"      => "required|min:2|max:80",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "unique"   => ":attribute已经存在",
        );
        $attributes = array(
            "name"      => "真实姓名",
            "telephone" => "联系电话",
            "leader"    => "部门老大",
            "desc"      => "部门简介",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //数据入库
        $clean = [
            'name'          => $data['name'],
            'telephone'     => $data['telephone'],
            'leader'        => $data['leader'],
            'desc'          => $data['desc'],
            'status'        => 1,
            'operator_id'   => $this->admin['id'],
            'operator_name' => $this->admin['name'],
            'created_at'    => date('Y-m-d H:i:s'),
        ];
        if (!StaffDept::insert($clean)) {
            return self::_json([], -1, '新增失败!');
        }
        return self::_json();
    }
    //
    public function dept_edit()
    {
        //动态验证发送过来的数据
        $rules = [
            "id"        => "required|exists:staff_dept",
            "name"      => "required|min:2|max:20",
            "telephone" => "required|min:2|max:20",
            "leader"    => "required|min:2|max:80",
            "desc"      => "required|min:2|max:80",
            "status"    => "required",
            "type"      => "",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "unique"   => ":attribute已经存在",
        );
        $attributes = array(
            "id"        => "用户ID",
            "name"      => "真实姓名",
            "telephone" => "联系电话",
            "leader"    => "部门老大",
            "desc"      => "部门简介",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //检查部门名称是否重复
        $_id = StaffDept::where('name', $data['name'])->pluck('id');
        //
        if (isset($_id) && ($data['id'] != $_id)) {
            return self::_json([], 1, '部门名称重复！');
        }
        //更新数据
        $clean = [
            'name'          => $data['name'],
            'telephone'     => $data['telephone'],
            'leader'        => $data['leader'],
            'desc'          => $data['desc'],
            'status'        => $data['status'],
            'operator_id'   => $this->admin['id'],
            'operator_name' => $this->admin['name'],
            'updated_at'    => date('Y-m-d H:i:s'),
        ];
        //
        if (!StaffDept::where('id', $data['id'])->update($clean)) {
            return self::_json([], -1, '更新失败!');
        }
        return self::_json();
    }
    //
    public function post()
    {
        $keys = ['rows', 'type', 'page', 'sort', 'order', 'name', 'status'];
        $data = $this->only($keys);
        if ($data['type'] == 'ajax') {
            $model = StaffPost::where(function ($query) use ($data) {
                if ($data['name']) {
                    $query->where('name', 'like', "%{$data['name']}%");
                }
                if ($data['status']) {
                    $status = $data['status'] == 2 ? 0 : $data['status'];
                    $query->where('status', $status);
                }
            });
            $depts = $model->orderBy($data['sort'], $data['order'])->paginate($data['rows']);
            $data  = [
                'total' => $depts->total(),
                'rows'  => $depts->getCollection(),
            ];
            return \Response::json($data);
        }
        $data = [];
        return View('admin.app.post', compact('data'));
    }
    //
    public function post_add()
    {
        //动态验证发送过来的数据
        $rules = [
            "name" => "required|min:2|max:20|unique:staff_post",
            "code" => "required|min:2|max:20",
            "desc" => "required|min:2|max:80",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "unique"   => ":attribute已经存在",
        );
        $attributes = array(
            "name" => "职称姓名",
            "code" => "职称编码",
            "desc" => "职称简介",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //数据入库
        $clean = [
            'name'          => $data['name'],
            'code'          => strtoupper($data['code']),
            'desc'          => $data['desc'],
            'status'        => 1,
            'operator_id'   => $this->admin['id'],
            'operator_name' => $this->admin['name'],
            'created_at'    => date('Y-m-d H:i:s'),
        ];
        if (!StaffPost::insert($clean)) {
            return self::_json([], -1, '新增失败!');
        }
        return self::_json();
    }
    //
    public function post_edit()
    {
        //动态验证发送过来的数据
        $rules = [
            "id"     => "required|exists:staff_post,id",
            "name"   => "required|min:2|max:20",
            "code"   => "required|min:2|max:20",
            "desc"   => "required|min:2|max:80",
            "status" => "required",
            "type"   => "",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "unique"   => ":attribute已经存在",
            "exists"   => ":attribute不存在",
        );
        $attributes = array(
            "id"   => "职称ID",
            "name" => "职称姓名",
            "code" => "职称编码",
            "desc" => "职称简介",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //检查部门名称是否重复
        $_id = StaffPost::where('name', $data['name'])->pluck('id');
        //
        if (isset($_id) && ($data['id'] != $_id)) {
            return self::_json([], 1, '部门名称重复！');
        }
        //更新数据
        $clean = [
            'name'          => $data['name'],
            'code'          => strtoupper($data['code']),
            'desc'          => $data['desc'],
            'status'        => $data['status'],
            'operator_id'   => $this->admin['id'],
            'operator_name' => $this->admin['name'],
            'updated_at'    => date('Y-m-d H:i:s'),
        ];
        //
        if (!StaffPost::where('id', $data['id'])->update($clean)) {
            return self::_json([], -1, '更新失败!');
        }
        return self::_json();
    }
}
